<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input
        v-model="ruleForm.username"
        type="username"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="密码" prop="userpwd">
      <el-input v-model="ruleForm.userpwd" type="userpwd" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup>
import { reactive, ref } from "vue";
import { userLogin } from "../model/user.js";
import { useRoute, useRouter } from "vue-router";
import { main } from "@popperjs/core";
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref();
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("用户名出错或为空"));
  } else {
    if (ruleForm.userpwd !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("userpwd", () => null);
    }
    callback();
  }
};
const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("密码出错或为空"));
  } else if (value !== ruleForm.username) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  userpwd: "",
});

const rules = reactive({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    {
      pattern: /^[a-z_$][a-z_$0-9]{2,9}$/i,
      message: "用户名只能以数字字母_$组成长度3到10位并且不能以数字开头",
      trigger: "blur",
    },
  ],
  userpwd: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 3, max: 10, message: "长度3到10位", trigger: "blur" },
  ],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let username = ruleForm.username;
      let userpwd = ruleForm.userpwd;
      let { data } = await userLogin({
        username,
        userpwd,
      });
      if (data.code == 200) {
        // console.log(data);
        let token = data.token;
        window.localStorage.setItem('token',token)
        // let menuList = data.menuList[0];
        router.push('/main')
        // console.log(menuList);
        // menuList.forEach((item) => {
        //   router.addRoute("main", {
        //     path: item.path,
        //     name: item.path,
        //     component: comInfo[item.com],
        //   }); //把字符串转成组件
        // });
        // console.log(router);
      } else {
        return alert(data.msg);
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style>
</style>
